package org.qpcr.community.auth.web.excel;

import com.alibaba.fastjson.JSONObject;
import lombok.Getter;
import lombok.Setter;
import org.hswebframework.reactor.excel.CellDataType;
import org.hswebframework.reactor.excel.ExcelHeader;
import org.hswebframework.web.authorization.Authentication;
import org.hswebframework.web.bean.FastBeanCopier;
import org.hswebframework.web.validator.ValidatorUtils;
import org.qpcr.community.auth.entity.OrganizationEntity;
import org.qpcr.community.auth.entity.RoleEntity;
import org.qpcr.community.auth.entity.UserDetail;
import org.qpcr.community.auth.service.request.SaveUserRequest;
import org.qpcr.core.metadata.Jsonable;
import org.qpcr.core.utils.IdUtils;

import javax.validation.constraints.Email;
import javax.validation.constraints.NotBlank;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Getter
@Setter
public class UserExcelInfo implements Jsonable {

    @org.qpcr.community.io.excel.annotation.ExcelHeader(value = "姓名")
    @NotBlank(message = "姓名不能为空")
    private String name;

    @org.qpcr.community.io.excel.annotation.ExcelHeader(value = "手机号")
    private String telephone;

    @org.qpcr.community.io.excel.annotation.ExcelHeader(value = "邮箱")
    @Email(message = "请输入正确的邮箱")
    private String email;

    @org.qpcr.community.io.excel.annotation.ExcelHeader(value = "角色")
    @NotBlank(message = "角色不能为空")
    private String role;

    @org.qpcr.community.io.excel.annotation.ExcelHeader(value = "组织")
    @NotBlank(message = "组织不能为空")
    private String org;

    @org.qpcr.community.io.excel.annotation.ExcelHeader(value = "用户名（账号）")
    @NotBlank(message = "用户名不能为空")
    private String username;

    @org.qpcr.community.io.excel.annotation.ExcelHeader(value = "密码")
    @NotBlank(message = "密码不能为空")
    private String password;

    @org.qpcr.community.io.excel.annotation.ExcelHeader(value = "用户类型")
    @NotBlank(message = "用户类型不能为空")
    private String roleType;

    private SaveUserRequest saveUserRequest = new SaveUserRequest();

    private Map<String, Object> configuration = new HashMap<>();

    private long rowNumber;

    private Boolean orgIsExist;
    private String orgId;
    private OrganizationEntity organizationSaveEntity = new OrganizationEntity();

    public Map<String,Object> toMap(){
        return FastBeanCopier.copy(this,new HashMap<>());
    }

    public static List<ExcelHeader> getTemplateHeaderMapping(UserExcelFilterColumns filterColumns) {
        return Arrays.stream(new ExcelHeader[]{
                        new ExcelHeader("item", "姓名", CellDataType.STRING),
                        new ExcelHeader("code", "手机号", CellDataType.STRING),
                        new ExcelHeader("channel", "邮箱", CellDataType.STRING),
                        new ExcelHeader("channel", "角色", CellDataType.STRING),
                        new ExcelHeader("channel", "组织", CellDataType.STRING),
                        new ExcelHeader("channel", "用户名（账号）", CellDataType.STRING),
                        new ExcelHeader("channel", "密码", CellDataType.STRING),
                        new ExcelHeader("channel", "用户类型", CellDataType.STRING)
                })
                .filter(a -> !filterColumns.getColumns().contains(a.getKey()))
                .collect(Collectors.toList());
    }

    public static List<ExcelHeader> getExportHeaderMapping(UserExcelFilterColumns filterColumns) {
        return Arrays.stream(new ExcelHeader[]{
                        new ExcelHeader("item", "姓名", CellDataType.STRING),
                        new ExcelHeader("code", "手机号", CellDataType.STRING),
                        new ExcelHeader("channel", "邮箱", CellDataType.STRING),
                        new ExcelHeader("channel", "角色", CellDataType.STRING),
                        new ExcelHeader("channel", "组织", CellDataType.STRING),
                        new ExcelHeader("channel", "用户名（账号）", CellDataType.STRING),
                        new ExcelHeader("channel", "密码", CellDataType.STRING),
                        new ExcelHeader("channel", "用户类型", CellDataType.STRING)
                })
                .filter(a -> !filterColumns.getColumns().contains(a.getKey()))
                .collect(Collectors.toList());
    }

    /**
     * 初始化保存实体
     *
     * @param userListDb               数据库已存在的数据
     * @param organizationEntityListDb 数据库已存在的数据
     * @param roleEntityListDb         数据库已存在的数据
     * @param auth                     认证数据
     * @return UserExcelInfo
     */
    public UserExcelInfo initTestItemInstance(List<UserDetail> userListDb, List<OrganizationEntity> organizationEntityListDb,
                                              List<RoleEntity> roleEntityListDb, Authentication auth) {
        String msg = "";
        List<UserDetail> list = userListDb.stream()
                .filter(db -> db.getUsername() != null && db.getUsername().equals(this.getUsername()))
                .collect(Collectors.toList());
        if (list.size() > 0) {
            msg += "用户名已存在 ";
        }
        List<RoleEntity> roleList = roleEntityListDb.stream()
                .filter(db -> db.getName() != null && db.getName().equals(this.getRole()))
                .collect(Collectors.toList());
        if (roleList.size() > 0) {
            saveUserRequest.setRoleIdList(Collections.singleton(roleList.get(0).getId()));
        } else {
            msg += "角色不存在 ";
        }
        if (!msg.isEmpty()) {
            throw new RuntimeException(msg);
        }

        List<OrganizationEntity> orgList = organizationEntityListDb.stream()
                .filter(db -> db.getName() != null && db.getName().equals(this.getOrg()))
                .collect(Collectors.toList());
        if (orgList.size() > 0) {
            saveUserRequest.setOrgIdList(Collections.singleton(orgList.get(0).getId()));
        } else {
            this.orgIsExist = false;
            this.orgId = IdUtils.newUUID();
            organizationSaveEntity.setId(orgId);
            organizationSaveEntity.setName(this.getOrg());
            saveUserRequest.setOrgIdList(Collections.singleton(this.orgId));
        }
        UserDetail userDetail = new UserDetail();
        userDetail.setUsername(this.getUsername());
        userDetail.setPassword(getPassword());
        userDetail.setName(this.getName());
        userDetail.setEmail(this.getEmail());
        userDetail.setTelephone(this.telephone);
        userDetail.setRoleType(this.roleType.equals("工程师用户") ? 1 : 0);
        saveUserRequest.setUser(userDetail);
        saveUserRequest.setRoleIdList(Collections.singleton(this.getRole()));

        ValidatorUtils.tryValidate(saveUserRequest);
        return this;
    }

    @Override
    public void fromJson(JSONObject json) {
        Jsonable.super.fromJson(json);
    }
}
